const _ = require('lodash')

function parseRule (rule, $) {
  if (!rule) return ''
  const [parseRule, regexRule] = rule.split('#')
  const rules = parseRule.split('@')
  rules.forEach((r) => {
    $ = simpleParser(r, $)
  })
  if (regexRule && typeof $ === 'string') {
    const regexRules = regexRule.split('|')
    regexRules.forEach(r => {
      $ = parseRegex($, r)
    })
  }
  return $
}

function parseRegex (text, regex) {
  const reg = new RegExp(regex)
  return text.replace(reg, '')
}

function selectorParse (rule, $, prefix = '') {
  const [tag, index] = rule.split('!')
  if (typeof $ === 'function') {
    $ = $(prefix + tag)
  } else {
    $ = $.find(prefix + tag)
  }
  if (index !== undefined) {
    $ = $.filter(i => i > index)
  }
  return $
}

function simpleParser (rule, $) {
  const rules = rule.split('.')
  switch (rules[0]) {
    case 'class':
      $ = selectorParse(rules[1], $, '.')
      break
    case 'id':
      $ = selectorParse(rules[1], $, '#')
      break
    case 'tag':
      $ = selectorParse(rules[1], $, '')
      break
    case 'text':
      $ = $.text()
      break
    case 'href':
    case 'src':
      $ = $.attr(rules[0])
      break
    case 'html':
      $ = $.html()
      break
    case 'textNodes':
      {
        const temp = []
        $.contents().each(function () {
          if (this.type === 'text') {
            const content = _.trim(this.data)
            content && (temp.push('<p>&nbsp;&nbsp;&nbsp;&nbsp;' + content + '</p>'))
          }
        })
        $ = temp.join('')
      }
      break
    default:
      throw new Error('unkonw rule: ' + rule)
  }
  if (rules[2]) {
    $ = $.eq(rules[2])
  }
  return $
}

module.exports = {
  parseRule
}
